package cn.jn.lhm.netty.part08.chat.config;

import cn.jn.lhm.netty.part08.chat.message.LoginRequestMessage;
import io.netty.channel.ChannelHandlerContext;

import java.util.Scanner;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/11/1 - 22:41
 **/
public class UserThread {

    private static final ExecutorService USER_THREAD = Executors.newFixedThreadPool(1);

    public static void initLogin(ChannelHandlerContext ctx) {
        CompletableFuture.runAsync(() -> {
            Scanner in = new Scanner(System.in);
            System.out.println("请输入用户名:");
            String username = in.nextLine().trim();
            System.out.println("请输入密码:");
            String password = in.nextLine().trim();
            LoginRequestMessage requestMessage = new LoginRequestMessage(username, password);
            ThreadLocalHolder.set(username);
            ctx.writeAndFlush(requestMessage);
        }, USER_THREAD);
    }

    public static void clear() {
        CompletableFuture.runAsync(ThreadLocalHolder::clear, USER_THREAD);
        USER_THREAD.shutdown();
    }

    public static String getUsername() {
        return CompletableFuture.supplyAsync(ThreadLocalHolder::get, USER_THREAD).join();
    }
}
